<script setup>
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {getSurveysApi} from "../../apis/SurveysApi.js";
import {Message,Notification} from "@arco-design/web-vue";
import useStore, {localGetUserLogin} from "../../store/index.js";
import __ from 'lodash'
import {submitAnswerApi} from "../../apis/AnswerApi.js";
import FingerprintJS from '@fingerprintjs/fingerprintjs';
import {getCurrentUser} from "../../apis/UserApi.js";
import {APP_NAME} from "../../config/index.js";
import PreviewFooter from "../../components/preview/PreviewFooter.vue";
import AllPreview from "../../components/preview/AllPreview.vue";

const defaultBg = new URL('../../assets/default-bg.png', import.meta.url).href;
const route = useRoute()
const router = useRouter()
const store = useStore()
const surveysId = ref(route.params.id)
const btnIsLoad = ref(false)
const loading = ref(false)
const surveyIsEmpty = ref(false)
const fpPromise = FingerprintJS.load();
//计时器
const timeObj = ref()

const submitTime = ref(0)
const surveys = ref({
    title: APP_NAME,
    description:'',
    questions:[],
    type:0
})
const surveysStyle = ref({
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
    backgroundImage: surveys.value.bgimg ?  "url(" + surveys.value.bgimg + ")" : `url(${defaultBg})`,
    backgroundPosition: 'left',
})

const submitAnswer = async () => {
    btnIsLoad.value = true
    // 生成浏览器指纹
    const fp = await fpPromise;
    const result = await fp.get();
    const browserFingerprint = result.visitorId; // 唯一标识符

    //循环遍历题目，判断题目类型，然后获取题目的答案，然后组成请求体
    let answerRequest = {
        surveyId: route.params.id,
        fingerprint: browserFingerprint,
        submitTime: submitTime.value,
        answerList: []
    }
    if (store.userIsLogin) {
        answerRequest.userId = store.userinfo.id
    }
    for (let question of surveys.value.questions) {
        let answer = {
            questionId: question.id,
            type: question.type
        }
        if (store.userIsLogin) {
            answer.userId = store.userinfo.id
        }
        //评分的value单独判断 数字
        if (question.type === 4 && question.required === 1){
            if (!question.value){
                btnIsLoad.value = false
                return Notification.error(`第${question.orders}题为必填`)
            }
        }else{
            if (question.required === 1 && __.isEmpty(question.value)) {
                btnIsLoad.value = false
                return Notification.error(`第${question.orders}题为必填`)
            }
        }

        //多选时转为 json字符串
        if (question.type === 1){
            if (__.isArray(question.value)){
                answer.value = JSON.stringify(question.value)
            }
        }else{
            answer.value = question.value
        }
        //评分转为字符串
        if (question.type === 4 && answer.value){
            answer.value = answer.value + ''
        }
        answerRequest.answerList.push(answer)
    }
    console.log('answerRequest', answerRequest)

    const res = await submitAnswerApi(answerRequest)
    btnIsLoad.value = false
    if (res.code === 0) {
        Notification.success('提交成功')
        await router.replace('/result')
    }else{
        Notification.error(res.message)
    }

}

onMounted(async () => {
    if (route.params.id){
        //检查路由上的id是否为数字
        if (__.isNaN(__.toNumber(route.params.id))){
            return Notification.error('id错误')
        }
        loading.value = true
        const res = await getSurveysApi(route.params.id)
        if(res.code === 0){
            surveys.value = res.data
            surveyIsEmpty.value = __.isEmpty(surveys.value.questions)
            //设置背景图
            surveysStyle.value.backgroundImage = surveys.value.bgimg ? "url(" + surveys.value.bgimg + ")": `url(${defaultBg})`
            if (surveys.value.isLogin === 1 ){
                if (!store.userIsLogin && localGetUserLogin()){
                    await getCurrentUser()
                }
                if (!store.userIsLogin){
                    Notification.error('请先登录')
                    await router.replace('/login?redirect=/preview/' + surveys.value.id)
                }
            }
            loading.value = false
            if (surveys.value.status === 2){
               return await router.replace("/result?status=2")
            }
            if (surveys.value.status === 0){
                return await router.replace("/result?status=0" )
            }
            //检查屏幕宽度 设置背景图位置
            if (window.innerWidth <= 768){
                surveysStyle.value.backgroundPosition = 'center'
            }else{
                surveysStyle.value.backgroundPosition = 'left'
            }

        }else{
            //TODO 跳转回首页
            Notification.error(res.message)
            loading.value = false
        }

        //开始记时
        timeObj.value = setInterval(() => {
            submitTime.value = submitTime.value + 1
        }, 1000)
    }
})
//页面关闭时销毁
window.onbeforeunload = () => {
    clearInterval(timeObj.value)
}

</script>

<template>
<div class="maxDiv w-full px-4 pb-24 pt-8 min-h-full" :style="surveysStyle">

<!--    <div class="logoDiv mb-4 flex h-[40px]">-->
<!--        <img src="../../assets/logo2.svg" >-->
<!--        <h2 class="appName">{{APP_NAME}}</h2>-->
<!--    </div>-->

        <div class="max-w-5xl mx-auto rounded border-2 bg-white shadow-lg">
            <div class="px-7">
                <h1 class="text-2xl text-center font-bold mt-4">{{surveys.title}}</h1>
                <p class="text-lg text-center my-3">{{surveys.description}}</p>

                <!--        每题问题-->
                <div v-for="question in surveys.questions" class="mt-5">
                    <AllPreview :question="question"/>
                </div>
                <a-spin class="w-full " :loading="loading" tip="加载中">
                    <div class="h-56" v-if="surveys.questions.length === 0 && surveyIsEmpty">
                        <a-result status="404" subtitle="问卷为空，快去添加问题吧！">
                        </a-result>
                    </div>
                </a-spin>
            </div>

            <div class="w-full mt-6">
                <div class="flex justify-center mb-8">
                    <a-button v-show="surveys.isTemplate !== 1 && surveys.questions.length > 0" class="w-52 ml-5"
                              type="primary" @click="submitAnswer" :loading="btnIsLoad">提交</a-button>
                    <a-button v-show="surveys.isTemplate === 1 || surveys.questions.length === 0" class="w-52 ml-5"
                              type="primary" @click="router.back()">返回</a-button>
                </div>
    <!--            底部栏-->
                <PreviewFooter :text="surveys.createUserName"/>
            </div>
        </div>
</div>
</template>

<style scoped>

.logoDiv{
    cursor: pointer;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    width: 130px;
    height: 35px;
}
.logoDiv img{
    width: 30px;
    height: 30px;
}
.appName{
    line-height: 30px;
    font-size: 15px;
    font-weight: bold;
}
</style>
